﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using Core.ProcessManager.Messenger;
using Core.ProcessManager.Process;

namespace Core.Process
{
    [Serializable]
    [XmlRoot("Process")]
    public class StandartProcess : IProcess
    {
        public string Name { get; set; }

        /// <summary>
        /// Список действий внутри процесса;
        /// </summary>
        private List<IAction> _actions = new List<IAction>();

       [XmlIgnore]
        public List<IAction> Actions
        {
            get { return _actions; }
            set { _actions = value; }
        }

        /// <summary>
        /// Поиск именованного действия в процессе;
        /// </summary>
        /// <param name="name">Имя действия</param>
        /// <returns>Действие, имя которого задано.</returns>
        [return: XmlIgnore]
        public IAction GetByName(string name)
        {
            return Actions
                .Where(a => a.Name == name)
                .FirstOrDefault();
        }

        /// <summary>
        /// Запуск процесса
        /// </summary>
        /// <param name="messenger">Оповещатель.</param>
        public void StartProcess(IMessenger messenger)
        {
            var counter = 0;
            var exist = true;

            Func<IAction, bool> myFunc = action => action.Execute(messenger);

            while (exist = true)
            {
                foreach (var action in Actions.Where(t => t.Level == counter))
                {
                    if (action == null)
                    {
                        exist = false;
                        break;
                    }

                    var r = myFunc.BeginInvoke(action, null, null);
                    myFunc.EndInvoke(r);
                }
                counter++;
            }
        }
    }
}